<?php

namespace app\admin\controller\jy;

use app\common\controller\Backend;
use think\Exception;

/**
 * 动态管理
 * @icon fa fa-circle-o
 */
class Blog extends Backend
{
    /**
     * Blog模型对象
     * @var \app\admin\model\jy\Blog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jy\Blog;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'user_id', 'public_time', 'images_count', 'status', 'nickname', 'avatar',
                    'blog_title', 'sub_title', 'blog_content', 'text_content', 'blog_images', 'scan_count',
                    'scan_user_count', 'share_count', 'share_user_count', 'praise_count', 'praise_user_count',
                    'create_time', 'update_time']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['id', 'nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return string
     * @throws Exception
     */
    public function add(): string
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);

            if (isset($params['user_id']) && $params['user_id'] != '0' && $params['user_id'] != '') {
                $user = model('\app\admin\model\User')->where(['id' => $params['user_id']])->find();
                if ($user) {
                    $params['nickname'] = $user['nickname'] ? $user['nickname'] : '';
                    $params['avatar'] = $user['avatar'] ? $user['avatar'] : '';
                } else {
                    $params['nickname'] = '';
                    $params['avatar'] = '';
                }
            }
            if ($params['nickname']) {
                $params['user_id'] = 0;
            }
            $blogContent = $params['blog_content'];
//            $h = new \app\admin\library\HTML2Text();
//            $blogText = $h->getText($blogContent);
            $params['text_content'] = self::getplaintextintrofromhtml($blogContent);

            $imageInfo = self::extract_attrib($blogContent);

            $params['images_count'] = count($imageInfo[3]);
            $params['blog_images'] = implode(',', $imageInfo[3]);
            $params['create_user'] = $this->auth->id;
            // 不定时发布
            if (!$params['public_time']) {
                $params['public_time'] = date("Y-m-d H:i:s", time());
            }
            // 定时发布
            if ($params['public_time'] > date("Y-m-d H:i:s", time())) {
                $params['status'] = 0;
            }
            $result = $this->model->allowField(true)->save($params);
            if (!$result) {
                $this->error(__('No rows were inserted'));
            }
            $this->success();
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return string
     * @throws Exception
     */
    public function edit($ids = null): string
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);

            if (isset($params['user_id']) && $params['user_id'] != '0' && $params['user_id'] != '') {
                $user = model('\app\admin\model\User')->where(['id' => $params['user_id']])->find();
                if ($user) {
                    $params['nickname'] = $user['nickname'] ? $user['nickname'] : '';
                    $params['avatar'] = $user['avatar'] ? $user['avatar'] : '';
                } else {
                    $params['nickname'] = '';
                    $params['avatar'] = '';
                }
            }
            if ($params['nickname']) {
                $params['user_id'] = 0;
            }
            $blogContent = $params['blog_content'];
//            $h = new \app\admin\library\HTML2Text();
//            $blogText = $h->getText($blogContent);
            $params['text_content'] = self::getplaintextintrofromhtml($blogContent);

            $imageInfo = self::extract_attrib($blogContent);

            $params['images_count'] = count($imageInfo[3]);
            $params['blog_images'] = implode(',', $imageInfo[3]);
            $params['update_user'] = $this->auth->id;
            // 定时发布
            if ($params['public_time'] > date("Y-m-d H:i:s", time())) {
                $params['status'] = 0;
            }
            $result = $row->allowField(true)->save($params);
            if (!$result) {
                $this->error(__('No rows were inserted'));
            }
            $this->success();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    function extract_attrib($html)
    {
        preg_match_all("/(href|src)=([\"|']?)([^\"'>]+.(jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG))/i", $html, $out, PREG_PATTERN_ORDER);
        return $out;
    }

    function getplaintextintrofromhtml($html)
    {
        // Remove the HTML tags
        $html = strip_tags($html);

        // Convert HTML entities to single characters
        $html = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
        $html_len = mb_strlen($html, 'UTF-8');

        // Make the string the desired number of characters
        // Note that substr is not good as it counts by bytes and not characters
        $html = mb_substr($html, 0, strlen($html), 'UTF-8');
        return $html;
    }
}